/*
Copyright (c) 2009, Young Digital Planet SA
All rights reserved.

* Redistribution and use in source and binary forms, with or without 
  modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this 
  list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, 
  this list of conditions and the following disclaimer in the documentation 
  and/or other materials provided with the distribution.
* Neither the name of the Young Digital Planet SA nor the names of its 
  contributors may be used to endorse or promote products derived from this 
  software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE 
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 
POSSIBILITY OF SUCH DAMAGE.
*/
package pl.ydp.utils{
	import flash.display.DisplayObject;
	import flash.display.Stage;
	import flash.events.KeyboardEvent;
	
	/**
	 * Singleton util for listening keyboard actions.
	 */
	public class KeyboardUtil{
		
		private static var _instance:KeyboardUtil;
		private var _pressedKeyCodes:Array;
		private var _stage:Stage;
		
		public function KeyboardUtil(pd:PrivateData, stage:Stage){
			_pressedKeyCodes = new Array();
			_stage = stage;
			
			initListeners(_stage);	
		}
		
		/**
		 * Getting instance of util.
		 * @param dObj display object which is used to find stage for adding keyboard listeners.
		 * @return instance of KeyboardUtil.
		 */
		public static function getInstance(dObj:DisplayObject):KeyboardUtil{			
			if(_instance == null){
				if(dObj.stage == null){
					throw new Error("Cannot initalize KeyboardListener, display object has null stage property");
				}else{
					_instance = new KeyboardUtil(new PrivateData(), dObj.stage);
				}
			}
			
			return _instance;
		}
		
		/**
		 * Indicates if key with given keyCode is now pressed.
		 * @param keyCode code of key which state should be examined.
		 * @param singleKey indicates if any other key can be pressed too.
		 */
		public function isKeyPressed(keyCode:uint, singleKey:Boolean = false):Boolean{
			if(_pressedKeyCodes.length == 0){
				return false;
			}else{
				var ind:int = _pressedKeyCodes.indexOf(keyCode);
				return  singleKey? ind != -1 && _pressedKeyCodes.length == 1:
									ind != -1;
			}
		}
		
		/**
		 * Indicates if keys with given keyCodes are pressed now.
		 * @param keyCombination array of key codes which should be examined.
		 */
		public function isKeyCombinationPressed(keyCombination:Array):Boolean{
			var count:int = 0;
			
			for each(var i:int in keyCombination){
				if(isKeyPressed(i))
					count++;
			}
			
			return count == keyCombination.length && 
					keyCombination.length == _pressedKeyCodes.length;
		}
		
		private function killInstance():void{
			if(_instance != null){
				_stage.removeEventListener(KeyboardEvent.KEY_DOWN, onKeyDownHandler);
				_stage.removeEventListener(KeyboardEvent.KEY_UP, onKeyUpHandler);
				_instance = null;
				_stage = null;
			}
		}
		
		/**
		 * Should be called when util is no longer used, to remove
		 * listeners from stage and nullify util instance.
		 */
		public static function dispose():void{
			if(_instance != null)
				_instance.killInstance();
		}
		
		private function initListeners(stage:Stage):void{
			stage.addEventListener(KeyboardEvent.KEY_DOWN, onKeyDownHandler);
			stage.addEventListener(KeyboardEvent.KEY_UP, onKeyUpHandler);
		}
		
		private function onKeyDownHandler(evt:KeyboardEvent):void{
			var ind:int = _pressedKeyCodes.indexOf(evt.keyCode);
			
			if(ind == -1)
				_pressedKeyCodes.push(evt.keyCode);
		}
		
		private function onKeyUpHandler(evt:KeyboardEvent):void{
			var ind:int = _pressedKeyCodes.indexOf(evt.keyCode);
			
			if(ind != -1)
				_pressedKeyCodes.splice(ind, 1);
		}
	}
}

class PrivateData{}